/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package roles;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.Serializable;
import users.*;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import model.DBManager;
import model.RolePermission;
import model.UserRole;

import java.lang.Boolean;

import model.Module;

import renderers.moduleComboBoxRenderer;

import java.util.*;

/**
 *
 * @author Aggelos
 */
public class EditRoleForm extends javax.swing.JFrame 
{
    EntityManager em;
    UserRole userRole1;
    boolean readOnly;
    
    boolean initialiseUpdate;
    
    RolePermission rp;

    
   
    /**
     * Creates new form EditUserForm
     */
    public EditRoleForm() 
    {
        em = DBManager.em;
        initComponents();
    }
    
     public EditRoleForm(UserRole ur, boolean readOnly, boolean update) 
     {
        em = DBManager.em;
        
        userRole1=ur;
        this.readOnly = readOnly;
        initComponents();
        
        initialiseUpdate  = update;
        if (initialiseUpdate)
           {
             updateInitialisation();
           }  
    }
    
     public void updateInitialisation()
     {      
         if( retrieveRolePermisionByUserRole(userRole1).isEmpty()) // αν η λιστα είναι  αδεια
           {
            // System.out.print("NULLLLL");
             rp = new RolePermission();
           }
         else   // αν η λιστα δεν ειναι αδεια
           {
             rp = retrieveRolePermisionByUserRole(userRole1).get(0);
  
             boolean isSelected=false;   
             if(rp.getCanCreate()== 1) { isSelected = true;}
             else if(rp.getCanCreate()==0){ isSelected=false;}
             canCreateCheckBox.setSelected(isSelected);


             if(rp.getCanRetrieve()== 1) {isSelected = true;}
             else if(rp.getCanRetrieve()==0){  isSelected=false;}
             canRetrieveCheckBox.setSelected(isSelected);

             if(rp.getCanUpdate()== 1){isSelected = true;}
             else if(rp.getCanUpdate()==0){ isSelected=false;}
             canUpdateCheckBox.setSelected(isSelected);

             if(rp.getCanDelete()== 1){isSelected = true;}
             else if(rp.getCanDelete()== 0){ isSelected=false;}
             canDeleteCheckBox.setSelected(isSelected);

             if(rp.getStationLevelAccess() == 1){isSelected = true;}
             else if(rp.getStationLevelAccess()== 0){ isSelected=false;}
             StationLevelAccessCheckBox.setSelected(isSelected);

             moduleComboBox.setSelectedIndex(rp.getModuleId().getId()-1);
           }
     }
     
      public List<RolePermission> retrieveRolePermisionByUserRole(UserRole user_role)
      {
          String idS =user_role.getId().toString();
          String strSQL="select * from ROLE_PERMISSION where ROLE_PERMISSION.ROLE_ID = "+idS;
          
          List<RolePermission> urList = em.createNativeQuery(strSQL,
                  RolePermission.class).getResultList() ;    
          return urList;
      }
     

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        userRole2 = userRole1;
        query1 = em.createQuery("select rp from RolePermission rp where rp.roleId=:userRole").setParameter("userRole",userRole2);
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        roleBoxRenderer1 = new avenue.RoleBoxRenderer();
        modulesQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT m2 FROM Module m2");
        modulesList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(modulesQuery.getResultList());
        moduleObject = new model.Module();
        moduleComboBoxRenderer1 = new renderers.moduleComboBoxRenderer();
        rolePermissionGUIObject = new model.RolePermission();
        roleNameLBL = new javax.swing.JLabel();
        roleNameTextField = new javax.swing.JTextField();
        jTextField1 = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        moduleLbl = new javax.swing.JLabel();
        moduleComboBox = new javax.swing.JComboBox();
        jSeparator2 = new javax.swing.JSeparator();
        canCreateCheckBox = new javax.swing.JCheckBox();
        canRetrieveCheckBox = new javax.swing.JCheckBox();
        canUpdateCheckBox = new javax.swing.JCheckBox();
        canDeleteCheckBox = new javax.swing.JCheckBox();
        jSeparator3 = new javax.swing.JSeparator();
        StationLevelAccessCheckBox = new javax.swing.JCheckBox();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        roleBoxRenderer1.setText("roleBoxRenderer1");

        moduleComboBoxRenderer1.setText("moduleComboBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        roleNameLBL.setText("Όνομα Ρόλου : ");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRole2, org.jdesktop.beansbinding.ELProperty.create("${roleName}"), roleNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextField1.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRole2, org.jdesktop.beansbinding.ELProperty.create("${id}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        moduleLbl.setText("Module:");

        moduleComboBox.setRenderer(moduleComboBoxRenderer1);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, modulesList, moduleComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, moduleObject, org.jdesktop.beansbinding.ObjectProperty.create(), moduleComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        canCreateCheckBox.setText("Create");
        canCreateCheckBox.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                canCreateCheckBoxActionPerformed(evt);
            }
        });

        canRetrieveCheckBox.setText("Retrieve");

        canUpdateCheckBox.setText("Update");
        canUpdateCheckBox.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                canUpdateCheckBoxActionPerformed(evt);
            }
        });

        canDeleteCheckBox.setText(" Delete");

        StationLevelAccessCheckBox.setText("STATION LEVEL ACCESS");
        StationLevelAccessCheckBox.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                StationLevelAccessCheckBoxActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(roleNameLBL)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(roleNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(StationLevelAccessCheckBox, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(moduleLbl)
                                .addGap(18, 18, 18)
                                .addComponent(moduleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(canCreateCheckBox)
                                .addGap(29, 29, 29)
                                .addComponent(canRetrieveCheckBox)
                                .addGap(44, 44, 44)
                                .addComponent(canUpdateCheckBox)
                                .addGap(18, 18, 18)
                                .addComponent(canDeleteCheckBox))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(saveButton)
                                .addGap(18, 18, 18)
                                .addComponent(cancelButton)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(roleNameLBL)
                    .addComponent(roleNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(canCreateCheckBox)
                    .addComponent(canRetrieveCheckBox)
                    .addComponent(canUpdateCheckBox)
                    .addComponent(canDeleteCheckBox))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(moduleLbl)
                    .addComponent(moduleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(StationLevelAccessCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 7, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
     
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
       this.setVisible(false); 
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        // TODO add your handling code here:
        
        System.out.println("update mesa sto save button "+initialiseUpdate);
///////////////////////////////////////////////////////       
        if(roleNameTextField.getText().isEmpty())
          {
            JOptionPane.showMessageDialog(this, "Παρακαλώ πληκτρολογείστε όνομα");
          }
        else
         {
           
               if(!em.getTransaction().isActive())
                {
                  em.getTransaction().begin();
                }
              
//           ///////////Eisagogi Onomatos Rolou
           userRole1.setRoleName(roleNameTextField.getText());
           em.persist(userRole1);
          // em.getTransaction().commit(); 

           if(initialiseUpdate == false )//diladi den kanoume update alla NEO
             { rp = new RolePermission(); }
           
          // rp = new RolePermission();
           rp.setCanCreate( canCreateCheckBox.isSelected()?  1 : 0  );
           rp.setCanRetrieve(canRetrieveCheckBox.isSelected()?  1 : 0 );
           rp.setCanUpdate(canUpdateCheckBox.isSelected()?  1 : 0);
           rp.setCanDelete(canDeleteCheckBox.isSelected()?  1 : 0);
           rp.setStationLevelAccess(StationLevelAccessCheckBox.isSelected()?  1 : 0); 

           Module tempModule  =  (Module) moduleComboBox.getSelectedItem();
           rp.setModuleId(tempModule);

           rp.setRoleId(userRole1);
           
           em.persist(rp);
           em.getTransaction().commit();

           MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
            for (WindowListener l : this.getWindowListeners()) 
              {
                l.windowClosed(we);
               }
           this.setVisible(false);

       }
 ////////////////////////////////////////////////////////////
    }//GEN-LAST:event_saveButtonActionPerformed

    private void canCreateCheckBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_canCreateCheckBoxActionPerformed
    {//GEN-HEADEREND:event_canCreateCheckBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_canCreateCheckBoxActionPerformed

    private void canUpdateCheckBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_canUpdateCheckBoxActionPerformed
    {//GEN-HEADEREND:event_canUpdateCheckBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_canUpdateCheckBoxActionPerformed

    private void StationLevelAccessCheckBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_StationLevelAccessCheckBoxActionPerformed
    {//GEN-HEADEREND:event_StationLevelAccessCheckBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_StationLevelAccessCheckBoxActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditRoleForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox StationLevelAccessCheckBox;
    private javax.swing.JCheckBox canCreateCheckBox;
    private javax.swing.JCheckBox canDeleteCheckBox;
    private javax.swing.JCheckBox canRetrieveCheckBox;
    private javax.swing.JCheckBox canUpdateCheckBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTextField jTextField1;
    private java.util.List<RolePermission> list1;
    private javax.swing.JComboBox moduleComboBox;
    private renderers.moduleComboBoxRenderer moduleComboBoxRenderer1;
    private javax.swing.JLabel moduleLbl;
    private model.Module moduleObject;
    private java.util.List<Module> modulesList;
    private javax.persistence.Query modulesQuery;
    private javax.persistence.Query query1;
    private avenue.RoleBoxRenderer roleBoxRenderer1;
    private javax.swing.JLabel roleNameLBL;
    private javax.swing.JTextField roleNameTextField;
    private model.RolePermission rolePermissionGUIObject;
    private javax.swing.JButton saveButton;
    private model.UserRole userRole2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
